//
//  FindHotPresenterViewController.m
//  Everest
//
//  Created by 李其昌 on 14/12/23.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "FindHotPresenterViewController.h"
#import "NetHandler.h"
#import "UIImageView+WebCache.h"
#import "HotPresenterCell.h"
#import "FindMayBeLikeUser.h"
#import "MJRefresh.h"
#import "HotPresenterHomepageController.h"
#import "UIColor+AddColor.h"
#import "JingRoundView.h"
#import "AvReadioPlayer.h"
#define kResues @"resues"
#define kTableFooterView @"footerView"
#define kCollectionRes @"adc"
#define kPage 1


@interface FindHotPresenterViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, JingRoundViewDelegate>

@property (nonatomic, retain) NSMutableArray *tittleArr;
@property (nonatomic, retain) NSMutableArray *mayBeLikeUserArr;
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) JingRoundView *roundView;
@property (nonatomic, retain) UIView *backView;
@end

@implementation FindHotPresenterViewController
- (void)dealloc
{
    [_tittleArr release];
    [_mayBeLikeUserArr release];
    [_myTableView release];
    [_roundView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tittleArr = [NSMutableArray array];
        self.mayBeLikeUserArr = [NSMutableArray array];
        self.page = 1;
        [self handleData];
    }
    return self;
}



- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_index?device=iPhone&page=1"];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
#warning 在这里判断data加菊花
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *allArr = [result objectForKey:@"list"];
        for (NSDictionary *dic in allArr) {
            [self.tittleArr addObject:[dic objectForKey:@"title"]];
            NSArray *childArr = [dic objectForKey:@"list"];
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *childDic in childArr) {
                FindMayBeLikeUser *find = [[FindMayBeLikeUser alloc] initWithDictionary:childDic];
                [find setValuesForKeysWithDictionary:dic];
                [arr addObject:find];
                [find release];
            }
            [self.mayBeLikeUserArr addObject:arr];
        }
//        NSLog(@"%@", self.mayBeLikeUserArr);
        [self.myTableView reloadData];
        
    }];
}

- (void)pullhandleData
{
    self.page = self.page + kPage;
//    NSLog(@"======%d", self.page);
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_index?device=iPhone&page=%ld", (long)self.page];
    NSLog(@"前%@", self.mayBeLikeUserArr);
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
#warning 在这里判断data加菊花
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *allArr = [result objectForKey:@"list"];
        for (NSDictionary *dic in allArr) {
            [self.tittleArr addObject:[dic objectForKey:@"title"]];
            NSArray *childArr = [dic objectForKey:@"list"];
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *childDic in childArr) {
                FindMayBeLikeUser *find = [[FindMayBeLikeUser alloc] initWithDictionary:childDic];
                [find setValuesForKeysWithDictionary:dic];
                [arr addObject:find];
                [find release];
            }
            [self.mayBeLikeUserArr addObject:arr];
        }
//        NSLog(@"%ld", (unsigned long)self.mayBeLikeUserArr.count);
        NSLog(@"后%@", self.mayBeLikeUserArr);
        [self.myTableView reloadData];
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    [super.navigationController setNavigationBarHidden:NO];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationItem.hidesBackButton = YES;
//    self.navigationItem.hidesBackButton = YES;
//    self.tabBarController.tabBar.hidden = YES;
    self.navigationItem.title = @"最火播主";
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, - 35, self.view.bounds.size.width, self.view.bounds.size.height + 35) style:UITableViewStyleGrouped];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kResues];
    [self setupRefresh];
    
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super.navigationController setNavigationBarHidden:NO];
    // 自定义tabbar
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49, self.view.bounds.size.width, 49)];
    [self.view addSubview:self.backView];
    self.backView.backgroundColor = [UIColor tabBarColor];
    // 返回键
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backView addSubview:backButton];
    backButton.frame = CGRectMake(10, 10, 30, 29);
    [backButton setImage:[UIImage imageNamed:@"iconfont-gerenfanhui.png"] forState:UIControlStateNormal];
    [backButton setTintColor:[UIColor sectionColor]];
    [backButton addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 播放键
    self.roundView = [JingRoundView defaultJingRoundView];
    self.roundView.frame = CGRectMake((self.view.bounds.size.width / 2) - 30, - 10, 60, 60);
    self.roundView.delegate = self;
    [self.backView addSubview:self.roundView];
    
}
// 自定义tabbar中播放按钮方法
-(void)playStatuUpdate:(BOOL)playState
{
    NSLog(@"%@...", playState ? @"播放": @"暂停了");
    if (playState == YES) {
        NSLog(@"播放");
        AvReadioPlayer *avPlayer = [AvReadioPlayer defaultAvPlayer];
        [avPlayer play];
    } else {
        NSLog(@"暂停");
        AvReadioPlayer *avPlayer = [AvReadioPlayer defaultAvPlayer];
        [avPlayer pause];
        
    }
}
- (void)backButtonClicked:(UIButton *)button
{
    NSLog(@"返回上一页");
    [self.navigationController popViewControllerAnimated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return self.view.bounds.size.height / 4.2;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width / 3 - 10, self.view.bounds.size.height / 4.2);
    UICollectionView *collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / 3) collectionViewLayout:flowLayout];
    collection.delegate = self;
    collection.dataSource = self;
    collection.tag = section;
    collection.backgroundColor = [UIColor whiteColor];
    [collection registerClass:[HotPresenterCell class] forCellWithReuseIdentifier:kCollectionRes];
    return collection;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = [self.mayBeLikeUserArr objectAtIndex:collectionView.tag];
    FindMayBeLikeUser *find = [arr objectAtIndex:indexPath.row];
    
    HotPresenterHomepageController *hotPresenterVC = [[HotPresenterHomepageController alloc] init];
    
    [self.navigationController pushViewController:hotPresenterVC animated:YES];
    
    hotPresenterVC.mayBeLikeUser = find;
    
    [hotPresenterVC release];
//    NSLog(@"%@", find.nickname);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotPresenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionRes forIndexPath:indexPath];
    NSArray *arr = [self.mayBeLikeUserArr objectAtIndex:collectionView.tag];
    FindMayBeLikeUser *find = [arr objectAtIndex:indexPath.row];
    [cell.myImageView setImageWithURL:[NSURL URLWithString:find.smallLogo]];
    cell.nickLabel.text = find.nickname;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tittleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kResues];
    cell.textLabel.text = [self.tittleArr objectAtIndex:indexPath.section];
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupRefresh
{
//    //    NSLog(@"进入了setupRefresh");
//    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
//    
//    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//    //进入刷新状态(一进入程序就下拉刷新)
//    [self.myTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
        [self.myTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    
    [self handleData];
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    [self pullhandleData];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView reloadData];
        [self.myTableView footerEndRefreshing];
    });
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
